/* eslint-disable */
<template>
  <div class="assignments-container">
    <div class="page-header">
      <h3>作业管理</h3>
      <el-button type="primary" @click="handleAdd">布置作业</el-button>
    </div>

    <el-table :data="assignments" style="width: 100%" v-loading="loading">
      <el-table-column prop="title" label="作业标题"></el-table-column>
      <el-table-column prop="class" label="班级"></el-table-column>
      <el-table-column prop="deadline" label="截止日期" width="180"></el-table-column>
      <el-table-column label="提交情况" width="120">
        <template slot-scope="scope">
          {{ scope.row.submittedCount }}/{{ scope.row.totalCount }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleView(scope.row)">查看提交</el-button>
          <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="作业标题" prop="title">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="班级" prop="class">
          <el-select v-model="form.class" placeholder="请选择班级">
            <el-option
              v-for="item in classes"
              :key="item.id"
              :label="item.name"
              :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="作业要求" prop="description">
          <el-input type="textarea" v-model="form.description" :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="截止日期" prop="deadline">
          <el-date-picker
            v-model="form.deadline"
            type="datetime"
            placeholder="选择截止日期"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="附件">
          <el-upload
            action="#"
            :auto-upload="false"
            :file-list="fileList"
            :on-change="handleFileChange">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 查看提交对话框 -->
    <el-dialog title="作业提交情况" :visible.sync="submissionDialogVisible" width="70%">
      <el-table :data="submissions" style="width: 100%">
        <el-table-column prop="studentId" label="学号"></el-table-column>
        <el-table-column prop="studentName" label="姓名"></el-table-column>
        <el-table-column prop="submitTime" label="提交时间"></el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === '已批改' ? 'success' : 'warning'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="分数"></el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleGrade(scope.row)">
              {{ scope.row.status === '已批改' ? '修改批改' : '批改' }}
            </el-button>
            <el-button size="mini" @click="handleDownload(scope.row)">下载</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 批改作业对话框 -->
    <el-dialog title="批改作业" :visible.sync="gradeDialogVisible" width="50%">
      <el-form :model="gradeForm" label-width="80px">
        <el-form-item label="分数">
          <el-input-number v-model="gradeForm.score" :min="0" :max="100"></el-input-number>
        </el-form-item>
        <el-form-item label="评语">
          <el-input type="textarea" v-model="gradeForm.comment" :rows="4"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="gradeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitGrade">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { 
  getCourseAssignments, 
  addAssignment, 
  updateAssignment, 
  deleteAssignment, 
  uploadAssignmentResource,
  getSubmissionsByAssignmentId,
  downloadSubmissionFile,
  getAssignmentDetail,
  gradeSubmission
} from '@/api/teacher'
import { mapGetters } from 'vuex'

export default {
  name: 'TeacherAssignments',
  data() {
    return {
      loading: false,
      assignments: [],
      dialogVisible: false,
      dialogTitle: '',
      submissionDialogVisible: false,
      gradeDialogVisible: false,
      classes: [
        { id: 1, name: '计算机2024级1班' }
      ],
      form: {
        id: '',
        title: '',
        class: '',
        description: '',
        deadline: '',
        courseId: '1', // 默认课程ID
        classId: '1',  // 默认班级ID
        resourceUrl: '' // 存储OSS文件URL
      },
      fileList: [],
      rules: {
        title: [
          { required: true, message: '请输入作业标题', trigger: 'blur' }
        ],
        class: [
          { required: true, message: '请选择班级', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请输入作业要求', trigger: 'blur' }
        ],
        deadline: [
          { required: true, message: '请选择截止日期', trigger: 'change' }
        ]
      },
      submissions: [],
      gradeForm: {
        score: 0,
        comment: ''
      },
      submitting: false, // 提交状态标记
      uploading: false,   // 上传状态标记
      currentAssignmentId: null
    }
  },
  computed: {
    ...mapGetters(['teacherInfo'])
  },
  created() {
    this.getAssignments()
  },
  methods: {
    // 获取作业列表
    getAssignments() {
      this.loading = true
      // 使用实际API调用获取作业列表
      getCourseAssignments(this.form.courseId, this.form.classId)
        .then(res => {
          if (res.code === 200) {
            console.log('获取作业列表成功:', res.data)
            this.assignments = res.data || []
          } else {
            this.$message.error(res.message || '获取作业列表失败')
          }
        })
        .catch(err => {
          console.error('获取作业列表出错:', err)
          this.$message.error('获取作业列表失败，请稍后重试')
        })
        .finally(() => {
        this.loading = false
        })
    },
    
    // 添加作业
    handleAdd() {
      this.dialogTitle = '布置作业'
      this.form = {
        id: '',
        title: '',
        class: '',
        description: '',
        deadline: '',
        courseId: '1',
        classId: '1',
        resourceUrl: ''
      }
      this.fileList = []
      this.dialogVisible = true
    },
    
    // 编辑作业
    handleEdit(row) {
      this.dialogTitle = '编辑作业'
      this.loading = true
      
      // 获取作业详情，确保获取完整的作业信息包括resourceUrl
      getAssignmentDetail(row.id)
        .then(res => {
          if (res.code === 200) {
            console.log('获取作业详情成功:', res.data)
            const assignment = res.data
            this.form = {
              id: assignment.id,
              title: assignment.title,
              class: assignment.className || '计算机2024级1班',
              description: assignment.description,
              deadline: assignment.deadline,
              courseId: assignment.courseId || '1',
              classId: assignment.classId || '1',
              resourceUrl: assignment.resourceUrl || ''
            }
            
            // 如果有资源URL，则显示在文件列表中
            if (assignment.resourceUrl) {
              this.fileList = [{
                name: this.getFileNameFromUrl(assignment.resourceUrl),
                url: assignment.resourceUrl
              }]
            } else {
              this.fileList = []
            }
            
      this.dialogVisible = true
          } else {
            this.$message.error(res.message || '获取作业详情失败')
          }
        })
        .catch(err => {
          console.error('获取作业详情出错:', err)
          this.$message.error('获取作业详情失败，请稍后重试')
        })
        .finally(() => {
          this.loading = false
        })
    },
    
    // 从URL中提取文件名
    getFileNameFromUrl(url) {
      if (!url) return '';
      
      try {
        // 直接从路径中提取文件名
        const urlObj = new URL(url);
        const pathParts = urlObj.pathname.split('/');
        const fileName = pathParts[pathParts.length - 1];
        
        // 文件名应该包含时间戳和原始文件名
        console.log('从URL提取的文件名:', fileName);
        return fileName;
      } catch (error) {
        // 如果URL解析失败，使用简单方法提取
        console.error('URL解析失败:', error);
        const parts = url.split('/');
        return parts[parts.length - 1];
      }
    },
    
    // 获取更易读的文件名（移除时间戳前缀）
    getOriginalFileName(url) {
      if (!url) return '无文件名';
      
      try {
        // 从URL中提取文件名
        const fileName = this.getFileNameFromUrl(url);
        
        // 如果文件名包含时间戳前缀（格式：时间戳_原始文件名.扩展名）
        if (fileName && fileName.includes('_')) {
          // 尝试移除时间戳前缀
          const parts = fileName.split('_');
          // 确保第一部分是时间戳（纯数字）
          if (parts.length > 1 && /^\d+$/.test(parts[0])) {
            // 返回时间戳后的部分（原始文件名）
            return parts.slice(1).join('_');
          }
        }
        
        return fileName;
      } catch (error) {
        console.error('获取原始文件名出错:', error);
        return '学生作业';
      }
    },
    
    // 删除作业
    handleDelete(row) {
      this.$confirm('确认删除该作业? 这将同时删除OSS中的文件资源', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteAssignment(row.id)
          .then(res => {
            if (res.code === 200) {
        this.$message.success('删除成功')
        this.getAssignments()
            } else {
              this.$message.error(res.message || '删除失败')
            }
          })
          .catch(err => {
            console.error('删除作业出错:', err)
            this.$message.error('删除失败，请稍后重试')
          })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    
    // 查看提交情况
    handleView(row) {
      // 保存当前作业ID，以便在批改后刷新
      this.currentAssignmentId = row.id;
      
      getSubmissionsByAssignmentId(row.id)
        .then(res => {
          if (res.code === 200) {
            if (res.data && res.data.length > 0) {
              // 按学生ID进行分组，只保留每个学生最新的提交记录
              const studentSubmissions = {};
              
              // 首先将所有提交按照学生ID分组
              res.data.forEach(submission => {
                const studentId = submission.studentId;
                // 如果这个学生ID之前没有提交记录，或者这条提交记录的时间更新
                if (!studentSubmissions[studentId] || 
                    new Date(submission.createTime || submission.submitTime) > 
                    new Date(studentSubmissions[studentId].createTime || studentSubmissions[studentId].submitTime)) {
                  studentSubmissions[studentId] = submission;
                }
              });
              
              // 将分组后只保留最新记录的对象转换为数组
              this.submissions = Object.values(studentSubmissions);
              console.log('去重后的提交列表:', this.submissions);
            } else {
              this.submissions = [];
            }
            this.submissionDialogVisible = true;
          } else {
            this.$message.error(res.message || '获取提交情况失败')
          }
        })
        .catch(err => {
          console.error('获取提交情况出错:', err)
          this.$message.error('获取提交情况失败，请稍后重试')
        })
    },
    
    // 处理文件变更 - 实现保存文件信息的逻辑
    handleFileChange(file, fileList) {
      console.log('文件变更:', file)
      // 验证文件大小和类型
      const isValid = this.validateFile(file)
      if (isValid) {
        // 只保留最后一个文件
        this.fileList = fileList.slice(-1)
      } else {
        // 移除无效文件
        this.fileList = fileList.filter(f => f !== file)
      }
    },
    
    // 验证文件
    validateFile(file) {
      // 验证文件大小上限20MB
      const isLt20M = file.size / 1024 / 1024 < 20
      if (!isLt20M) {
        this.$message.error('文件大小不能超过20MB')
        return false
      }
      
      // 可以添加文件类型检查，例如只允许doc, pdf等
      const fileName = file.name.toLowerCase()
      const validExtensions = ['.pdf', '.doc', '.docx', '.zip', '.rar', '.ppt', '.pptx', '.xls', '.xlsx', '.txt']
      const isValidType = validExtensions.some(ext => fileName.endsWith(ext))
      
      if (!isValidType) {
        this.$message.warning('建议上传常见文档格式如pdf, doc, docx, ppt等')
      }
      
      return true
    },
    
    // 批改作业
    handleGrade(row) {
      this.gradeForm = {
        id: row.id,
        studentId: row.studentId,
        score: row.score || 0,
        comment: row.comment || ''
      }
      this.gradeDialogVisible = true
    },
    
    // 下载学生作业
    handleDownload(row) {
      if (!row.fileUrl) {
        this.$message.warning('文件不存在')
        return
      }
      
      // 获取原始文件名或使用默认文件名
      let fileName = this.getOriginalFileName(row.fileUrl);
      
      // 创建一个隐藏的a标签
      const link = document.createElement('a')
      link.href = row.fileUrl
      link.download = fileName
      link.target = '_blank'
      document.body.appendChild(link)
      link.click()
      
      // 移除创建的元素
      setTimeout(() => {
        document.body.removeChild(link)
      }, 100)
      
      this.$message.success('开始下载文件')
    },
    
    // 提交作业表单 - 实现文件上传和保存的完整逻辑
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.submitting) {
            return
          }
          
          this.submitting = true
          
          // 显示加载提示
          const loading = this.$loading({
            lock: true,
            text: '正在提交...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          
          // 定义保存作业信息的方法
          const saveAssignment = () => {
            // 组装作业数据
            const assignmentData = {
              title: this.form.title,
              description: this.form.description,
              deadline: this.form.deadline,
              courseId: this.form.courseId,
              classId: this.form.classId,
              resourceUrl: this.form.resourceUrl || '', // 确保resourceUrl被包含
              teacherId: this.teacherInfo?.id || '1001' // 默认教师ID
            }
            
            console.log('保存作业数据:', assignmentData)
            
            // 根据是否有ID判断是新增还是更新
            const savePromise = this.form.id 
              ? updateAssignment(this.form.id, assignmentData)
              : addAssignment(assignmentData)
            
            return savePromise
          }
          
          // 检查是否有新文件需要上传
          const hasNewFile = this.fileList.length > 0 && this.fileList[0].raw
          
          if (hasNewFile) {
            // 有新文件需要上传
            const file = this.fileList[0].raw
            console.log('准备上传文件:', file.name)
            
            // 上传文件
            this.uploading = true
            uploadAssignmentResource(file)
              .then(res => {
                this.uploading = false
                
                if (res.code === 200) {
                  const fileUrl = res.data;
                  
                  // 增强URL验证
                  if (!fileUrl || typeof fileUrl !== 'string') {
                    throw new Error('服务器返回的文件URL无效');
                  }
                  
                  // 检查是否是合法的URL
                  if (!fileUrl.startsWith('http') || !fileUrl.includes('/')) {
                    console.error('警告: 服务器返回的URL格式异常:', fileUrl);
                    throw new Error(`服务器返回的URL格式异常: ${fileUrl}`);
                  }
                  
                  console.log('文件上传成功, 获得URL:', fileUrl);
                  
                  // 更新表单中的资源URL
                  this.form.resourceUrl = fileUrl;
                  
                  // 保存作业信息
                  return saveAssignment();
                } else {
                  throw new Error(res.message || '文件上传失败');
                }
              })
              .then(res => {
                loading.close()
                this.submitting = false
                
                if (res.code === 200) {
                  this.$notify({
                    title: '成功',
                    message: `作业已${this.form.id ? '修改' : '发布'}成功，作业文件URL已保存`,
                    type: 'success',
                    duration: 3000
                  })
                  this.dialogVisible = false
                  this.getAssignments()
                } else {
                  throw new Error(res.message || '作业保存失败')
                }
              })
              .catch(err => {
                loading.close()
                this.submitting = false
                console.error('提交作业出错:', err)
                this.$message.error(err.message || '操作失败，请稍后重试')
              })
          } else {
            // 没有新文件需要上传，直接保存作业信息
            // 注意：保留之前的resourceUrl，确保编辑时不会丢失
            saveAssignment()
              .then(res => {
                loading.close()
                this.submitting = false
                
                if (res.code === 200) {
          this.$message.success(this.form.id ? '修改成功' : '发布成功')
          this.dialogVisible = false
          this.getAssignments()
                } else {
                  throw new Error(res.message || '作业保存失败')
                }
              })
              .catch(err => {
                loading.close()
                this.submitting = false
                console.error('提交作业出错:', err)
                this.$message.error(err.message || '操作失败，请稍后重试')
              })
          }
        }
      })
    },
    
    // 提交批改
    submitGrade() {
      // 直接调用API批改作业
      gradeSubmission(
        this.gradeForm.id, 
        this.gradeForm.score || 0,
        this.gradeForm.comment || '',
        this.teacherInfo?.id || '1001'
      )
        .then(res => {
          if (res.code === 200) {
            this.$message.success('批改成功')
            this.gradeDialogVisible = false
            // 刷新提交列表
            if (this.currentAssignmentId) {
              this.handleView({id: this.currentAssignmentId})
            }
          } else {
            this.$message.error(res.message || '批改失败')
          }
        })
        .catch(err => {
          console.error('批改提交出错:', err)
          this.$message.error('批改失败，请稍后重试')
        })
    }
  }
}
</script>

<style scoped>
.assignments-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h3 {
  margin: 0;
}
</style> 